
var stub = {};
stub.callbacks = {};

stub.api = {
	callEx: function(apiName, params){
		var dtd = $.Deferred();

		var requestId = grantId();
		var request = {
			"action" : "api.call",
			"echo" : requestId,
			"params" : [apiName, params]
		};
		stub.callbacks[requestId] = dtd;
		chrome.extension.sendMessage(request);
		return dtd.promise();
	}
};

stub.base = (function(){
	var Error = function(message, code){
		this.message = message;
		this.code = code;
	};

	return {
		Error: Error
	};
})();

function grantId() {
	while(true) {
		var rand = Math.random();
		if (typeof stub.callbacks[rand] == "undefined") {
			return rand;
		}
	}
}

chrome.extension.onRequest.addListener(function(request, sender){
	if (request.action == "stub_response") {
		var requestId = request.echo;
		var dtd = stub.callbacks[requestId];
		if (dtd) {
			if (request.status == "success") {
				dtd.resolve(request.data);
			} else if (request.status == "fail") {
				dtd.reject(new stub.base.Error(request.data.message, request.data.code));
			}
		}
	}
});